<?php

declare(strict_types=1);

namespace app\controller\admin;

use app\model\admin\Product;
use app\model\admin\ProductAttr;
use app\model\admin\ProductAttrResult;
use app\model\admin\ProductAttrValue;
use app\model\admin\ProductCate;
use Error;
use think\facade\Db;
use think\facade\Validate;
use think\Request;

class ProductController extends AdminBaseController
{
    /**
     * 显示资源列表
     *
     * @return \think\Response
     */
    public function index(Request $request)
    {
        $params = $request->param();
        // 'cates.cate'
        $list = Product::scope('where', $params)
            ->with(['cate'])
            ->order('id', 'desc')->paginate([
                'list_rows' => $this->limit,
                'page' => $this->page,
                'var_page' => $this->pageVar
            ]);
        $arr = $list->items();
        foreach ($arr as $key => $val) {
            $temp = [];
            $val['cate_name'] = "";
            // foreach ($val->cates as $k => $v) {
            //     array_push($temp, $v->cate->name ?? '');
            //     $val['cate_name'] = implode(",", $temp);
            // }
        }
        return successPage($list);
    }

    /**
     * 添加或修改产品
     *
     * @return \think\Response
     */
    public function save(Request $request)
    {
        //
        $params = $request->param();
        storage_log("商品添加或修改参数：" . json_encode($params));
        $validate = Validate::rule([
            "cate_id" => "require",
            "goods_name" => "require",
            "unit_name" => "require",
            "slider_image" => "require",
            "status" => "require",
            "spec_type" => "require",
            "freight" => "require",
            // "postage" => "require",
            // "store_info" => "require",
            "sort" => "require",
            // "keyword" => "require",


            // "temp_id" => "require",
            // "limit_type" => "require",
            // "limit_num" => "require",
        ]);
        // todo

        // 检验参数
        if (!$validate->check($params)) {
            return error($validate->getError());
        }

        // 处理逻辑
        try {
            Db::transaction(function () use ($params) {
                // 添加商品
                if ($params['spec_type'] === 1) {
                    // 多规格
                    $manyList = $params['attrs'] ?? [];
                    $minPrice = searchMin($manyList, "price");
                    // 原价获取最大
                    $market_price = searchMax($manyList, "market_price");
                    // 库存累积
                    $stock = array_sum(array_column($manyList, "stock"));
                    // 成本获取最大
                    $cost = searchMax($manyList, "cost");
                } else {
                    $minPrice = $params['attrs'][0]['price'];
                    $market_price = $params['attrs'][0]['market_price'];
                    $stock = $params['attrs'][0]['stock'];
                    $cost = $params['attrs'][0]['cost'];
                    // $minPrice = $params['price'];
                    // $market_price = $params['market_price'];
                    // $stock = $params['stock'];
                    // $cost = $params['cost'];
                }

                $productData = [
                    "slider_image" => $params['slider_image'],
                    "goods_name" => $params['goods_name'],
                    "store_info" => $params['store_info'] ?? "",
                    "keyword" => $params['keyword'] ?? "",
                    "cate_id" => $params['cate_id'],
                    "price" => $minPrice,
                    "market_price" => $market_price,
                    "unit_name" => $params['unit_name'],
                    "sort" => $params['sort'],
                    "ficti" => $params['ficti'],
                    "stock" => $stock,
                    "status" => $params['status'],
                    "freight" => $params['freight'],
                    "cost" => $cost,
                    "spec_type" => $params['spec_type'],
                    "custom_form" => $params['custom_form'],
                    "is_limit" => $params['is_limit'] ?? 0,
                    "limit_type" => $params['limit_type'] ?? null,
                    "limit_num" => $params['limit_num'] ?? null,
                    "min_qty" => $params['min_qty'] ?? 1,
                    "description" => $params['description'] ?? "",
                ];
                if (isset($params['image']) && $params['image']) {
                    $productData['image']  = $params['image'];
                } else {
                    $productData['image']  = $params['slider_image'][0];
                }


                if ($params['freight'] == 2) {
                    // 固定运费
                    $productData['postage'] = $params['postage'];
                } else {
                    // 运费模版
                    $productData['temp_id'] = $params['temp_id'];
                }
                if (isset($params['id'])) {
                    // 编辑
                    $product_id = $params['id'];

                    // unset 不写入的数据 
                    // todo 库存 如何处理


                    // todo 更新表
                    $product = Product::find($product_id);
                    if (!$product) {
                        throw new Error('产品id不匹配');
                    }
                    Product::update($productData, [
                        "id" => $product_id
                    ]);

                    ProductAttr::where('product_id', $product_id)->delete();
                    ProductAttrValue::where('product_id', $product_id)->delete();
                    ProductAttrResult::where('product_id', $product_id)->delete();
                    ProductCate::where('product_id', $product_id)->delete();
                } else {
                    // 创建产品表
                    $product = Product::create($productData);
                    $product_id = $product->id;
                }
                // 创建产品分类表

                foreach ($params['cate_id'] as $key => $val) {
                    ProductCate::create([
                        "product_id" => $product_id,
                        "cate_id" => $val,
                    ]);
                }

                // 创建规格表
                if ($params['spec_type'] == 1) {
                    // 多规格 ,用于前端表头
                    $attr = [];
                    $value = [];

                    foreach ($params['items'] as $key => $val) {
                        $temp = [
                            "product_id" => $product_id,
                            "attr_name" => $val['value'],
                            "attr_values" =>  $val['detail'],
                        ];
                        ProductAttr::create($temp);
                        array_push($attr, [
                            "value" => $val['value'],
                            "detail" => $val['detail'],
                        ]);
                    }

                    //
                    foreach ($params['attrs'] as $key => $val) {
                        $val['product_id'] = $product_id;
                        // sku 
                        $sku = [];
                        $detail = [];
                        foreach ($val as $k => $v) {
                            // 5是value的长度
                            $index = substr($k, 5);
                            if (!strstr($k, 'value')) {
                                continue;
                            }
                            $detail[$params['items'][intval($index) - 1]['value']] = $v;
                            // var_dump($detail);
                            // $sku .= $v;
                            array_push($sku, $v);
                        }
                        // var_dump($detail);
                        $val['detail'] = $detail;
                        array_push($value, $val);
                        // $val['sku'] = implode(',', $sku);
                        $val['sku'] = $sku;
                        $val['image'] = $val['pic'];
                        // 设置唯一值 （同一商品下唯一）
                        // var_dump()
                        $val['unique'] = $product_id . "-" . implode(',', $sku);

                        ProductAttrValue::create($val);
                    }

                    // var_dump(json_encode([
                    //     "attr" => $attr,
                    //     "value" => $value,
                    // ]));
                    // product_attr 和 product_attr_value 汇合表
                    ProductAttrResult::create([
                        "product_id" => $product_id,
                        "result" => [
                            "attr" => $attr,
                            "value" => $value,
                        ],
                    ]);
                } else {
                    // 单规格
                    ProductAttr::create([
                        "product_id" => $product_id,
                        "attr_name" => "规格",
                        "attr_values" => "默认",
                    ]);
                }
            });
        } catch (\Exception $e) {
            // var_dump($e);
            return error($e->getMessage());
        }
        return success();
    }

    /**
     * 保存新建的资源
     *
     * @param  \think\Request  $request
     * @return \think\Response
     */
    // public function save(Request $request)
    // {
    //     //
    // }

    /**
     * 显示指定的资源
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function detail($id)
    {
        //
        $product = Product::with([
            "cates",
            "attrKey",
            "attrRes",
            "attrValue",
        ])->find($id);
        if (!$product) {
            return error("产品未找到");
        }
        if ($product->attrRes) {
            // $product->attrs = $product->attrRes->result['value'];
            $product->items = $product->attrRes->result['attr'];
        }
        foreach ($product->attrValue as $key => &$val) {
            foreach ($val['sku'] as $k => $v) {
                $val['value' . intval($k) + 1] = $v;
            }
        }


        return success($product);
    }

    /**
     * 显示编辑资源表单页.
     *
     * @param  int  $id
     * @return \think\Response
     */
    // public function edit($id)
    // {
    //     //
    // }

    /**
     * 保存更新的资源
     *
     * @param  \think\Request  $request
     * @param  int  $id
     * @return \think\Response
     */
    // public function update(Request $request, $id)
    // {
    //     //
    // }
    // 修改状态
    public function changeStatus($id, Request $request)
    {
        $id = input('id');
        $info = Product::where('id', $id)->find();
        if (!$info) {
            return error('记录不存在');
        }
        // var_dump($info);

        if ($info->status == 1) {
            // $info->status = 0;
            $status = 0;
        } else {
            // $info->status = 1;
            $status = 1;
        }
        // var_dump($status, $id);
        // $info->save();
        $res = Db::table('product')->where('id', $id)->update([
            "status" => $status
        ]);
        // var_dump($res);
        return success();
    }
    /**
     * 删除指定资源
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function delete($id)
    {
        //
    }
}
